# -*- coding: utf-8 -*-
__author__ = 'yangq'

from appcommon.appinstance import mysql_app_pool
from common import timetool
from tornado import gen


@gen.coroutine
def add_news_2_mysql(title, content, operate_user, create_time, is_first, type):
    sql = (
        "insert into app_news_info (title, content, operate_user, create_time, is_first, type) "
        u"values ('{}', %s, '{}', {}, {}, {})"
    )
    yield mysql_app_pool.update(sql.format(
        title, operate_user, create_time, is_first, type
    ), content)
    res = True

    raise gen.Return(res)


@gen.coroutine
def update_news_2_mysql(title, content, news_id, current_time):
    sql = u"update app_news_info set title = '{}', content=%s, create_time={}  where id = {} "
    res = yield mysql_app_pool.update(sql.format(title,current_time, news_id), content)
    raise gen.Return(res)


@gen.coroutine
def del_news_from_mysql(news_id):
    sql = (
        "delete from app_news_info  where id = {}"
    )
    try:
        yield mysql_app_pool.delete(sql.format(news_id))
        res = True
    except Exception, e:
        print e
        res = False
    raise gen.Return(res)


@gen.coroutine
def get_news_list(type, sort, rows, page, order):
    sql = (
        "select id as news_id, title,create_time as pubtime, is_first from app_news_info "
        "where type={} and is_using=1 order by create_time desc"
    )
    res = yield mysql_app_pool.get_all(sql.format(type), cursor='dict')
    start = (int(page) - 1) * int(rows)
    info = (res[start:start + int(rows)], len(res))
    raise gen.Return(info)


@gen.coroutine
def get_news_detail(news_id):
    sql = "select id as news_id, title,create_time as pubtime, content from app_news_info where id={} and is_using=1"
    info = yield mysql_app_pool.get_one(sql.format(news_id), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def get_push_info_id(current_time):
    sql = "select id  from app_news_info where create_time={} and is_using=1 and type=1"
    info = yield mysql_app_pool.get_one(sql.format(current_time), cursor='dict')
    raise gen.Return(info['id'])


@gen.coroutine
def add_psuh_task(type, info_id):
    current_time = timetool.get_timestamp()
    sql = (
        "insert into app_push_task (info_id, type, status, create_time) values ({}, {}, 0, {})"
    )
    res = yield mysql_app_pool.insert_one(sql.format(
        info_id, type, current_time
    ))
    raise gen.Return(res)


@gen.coroutine
def news_to_circle(news_id, is_first):
    sql = (
        "update app_news_info set is_first = {} where id = {}"
    )
    yield mysql_app_pool.update(sql.format(is_first, news_id))
    raise gen.Return({})